package cn.mily.user.interceptor;

import cn.mily.basics.utils.JsonResult;
import cn.mily.user.domain.LoginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class Interceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     *  用户拦截器
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        /*判断请求头里是否含token*/
        if(!StringUtils.isEmpty(request.getHeader("token"))){
            /*查询redis中数据存在否*/
            LoginInfo loginInfo = (LoginInfo) redisTemplate.opsForValue().get(request.getHeader("token"));
            if(loginInfo!=null){
                /*重新设置有效期*/
                redisTemplate.opsForValue().set(request.getHeader("token"), loginInfo,5, TimeUnit.MINUTES);
                return true;
            }
        }
        /*响应信息*/
        loginResponse(response);
        return false;
    }

    /*设置响应*/
    private void loginResponse(HttpServletResponse response) throws IOException {
        /*设置响应类容*/
        response.setContentType("text/json;charset=utf-8");
        /*获取输出流*/
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noUser\"}");
    }
}
